<template>
  <view class="container">
    <view class="demo-container rounded w-full mb-4">
      <view class="content w-full image-list mb-2" v-if="fileList && fileList.length">
        <view v-for="(item, index) in fileList" :key="index" class="image-item">
          <image :src="item" class="file-preview w-full mr-2 rounded" v-if="fileName==='img'"></image>
          <video
            :src="item"
            v-else-if="fileName==='video'"
            class="file-preview w-full mr-2 rounded"
            controls
          ></video>
        </view>
      </view>
      <view class="content w-full upload-trigger tac rounded" @click="chooseFile">
        <van-icon :name="iconName" size="30rpx" color="#515a6e" />
        <view class="font-sm mt-2">{{ desc }}</view>
      </view>
    </view>
  </view>
</template>

<script>
import {IMG_URL} from '../../../config/index';

export default {
  props: {
    count: {
      type: Number,
      default: 6,
    },
    fileList: {
      type: Array,
      default: () => [],
    },
    desc: {
      type: String,
      default: '上传图片',
    },
    fileName: {
      type: String,
      default: 'img',
    },
    iconName: {
      type: String,
      default: 'photograph',
    },
    sourceType: {
      type: Array,
      default: () => ['album', 'camera'],
    },
    extension: {
      type: String,
      default: 'jpg,jpeg,png,gif,bmp,raw,dng,cr2,nef,nrw,raf,arw,dng',
    },
  },
  data() {
    return {
      fileTempPaths: [],
    };
  },
  methods: {
    chooseFile() {
      let count = this.count;
      if (this.fileName === 'img' && this.fileList.length >= 3) {
        uni.showToast({
          title: '最多上传3张图片',
          icon: 'none',
          duration: 2000,
        });
        return;
      } else if (this.fileName === 'video' && this.fileList.length >= 1) {
        uni.showToast({
          title: '最多上传1个视频',
          icon: 'none',
          duration: 2000,
        });
        return;
      } else if (this.fileName === 'img') {
        count = 3 - this.fileList.length; // 确保最多上传3张图片
      } else if (this.fileName === 'video') {
        count = 1 - this.fileList.length; // 确保最多上传1个视频
      }

      if (this.fileName === 'img') {
        uni.chooseImage({
          count: count,
          sizeType: ['original', 'compressed'],
          sourceType: this.sourceType,
          success: (res) => {
            uni.showLoading({
              title: '图片上传中',
            });
            this.fileTempPaths = this.fileTempPaths.concat(res.tempFilePaths);
            this.$emit('onUpload', this.fileTempPaths);
            this.uploadFiles(res.tempFilePaths);
          },
          fail: (err) => {
            uni.getSetting({
              success: (res) => {
                const authStatusAlbum = res.authSetting['scope.album'];
                if (!authStatusAlbum) {
                  uni.showModal({
                    title: '授权失败',
                    content: '需要从您的相册获取图片，请在设置界面打开相关权限',
                    success: (modalRes) => {
                      if (modalRes.confirm) {
                        uni.openSetting();
                      }
                    },
                  });
                }
              },
            });
          },
        });
      } else if (this.fileName === 'video') {
        uni.chooseVideo({
          sourceType: this.sourceType,
          maxDuration: 60,
          camera: 'back',
          success: (res) => {
            uni.showLoading({
              title: '视频上传中',
            });
            this.fileTempPaths = this.fileTempPaths.concat(res.tempFilePath);
            this.$emit('onUpload', this.fileTempPaths);
            this.uploadFiles([res.tempFilePath]);
          },
          fail: (err) => {
            uni.getSetting({
              success: (res) => {
                const authStatusCamera = res.authSetting['scope.camera'];
                if (!authStatusCamera) {
                  uni.showModal({
                    title: '授权失败',
                    content: '需要使用摄像头拍摄视频，请在设置界面打开相关权限',
                    success: (modalRes) => {
                      if (modalRes.confirm) {
                        uni.openSetting();
                      }
                    },
                  });
                }
              },
            });
          },
        });
      }
    },
    uploadFiles(filePaths) {
      const uploadPromises = filePaths.map((filePath) => {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: IMG_URL + '/api/frontApph7/frontCommon/upload', // 替换为你的上传接口
            filePath: filePath,
            name: 'file', // 服务器接收文件时对应的字段名
            formData: {
              // 其他需要上传的表单数据
            },
            success: (res) => {
              uni.hideLoading();
              if (res.statusCode === 200) {
                try {
                  const data = JSON.parse(res.data);
                  if (data.code === 200) {
                    resolve(data); // 上传成功，解析并返回整个 data 对象
                  } else {
                    reject(data.message || '上传失败'); // 上传失败，返回错误消息
                  }
                } catch (e) {
                  reject('解析上传结果失败'); // 解析失败，返回错误消息
                }
              } else {
                reject(`上传失败，状态码：${res.statusCode}`); // 上传失败，返回状态码
              }
            },
            fail: (err) => {
              uni.hideLoading();
              reject(err); // 上传失败，返回错误信息
            },
          });
        });
      });

      Promise.all(uploadPromises)
        .then((results) => {
          console.log('所有文件上传成功', results);
          uni.showToast({
            title: '上传成功',
            icon: 'success',
            duration: 2000,
          });
          this.$emit('onUploadSuccess', results); // 发射成功事件，传递结果数据
        })
        .catch((error) => {
          console.error('上传失败', error);
          uni.showToast({
            title: error,
            icon: 'none',
            duration: 3000,
          });
          this.$emit('onUploadFail', error); // 发射失败事件，传递错误信息
        });
    },
  },
};
</script>

<style>
.container {
  padding: 20rpx;
}

.demo-container {

}

.image-list {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20rpx;
}

.image-item {
  position: relative;
  width: 220rpx;
  height: 220rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

.file-preview {
  width: 220rpx;
  height: 220rpx;
}

.upload-trigger {
  height: 220rpx;
  width: 220rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ebedf0;
  border-radius: 10rpx;
  flex-direction: column;
}

.tac {
  text-align: center;
}

.mt-2 {
  margin-top: 20rpx;
}

.mb-2 {
  margin-bottom: 20rpx;
}

.mb-4 {
  margin-bottom: 40rpx;
}

.w-full {
  width: 100%;
}

.rounded {
  border-radius: 20rpx;
}

.font-sm {
  font-size: 28rpx;
  color: #515a6e;
}
</style>
